//qqMsgTray.c
#include <gtk/gtk.h>
#include <stdlib.h>
#include <string.h>

#include <stdarg.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <signal.h>
#include <getopt.h>
#include <libgen.h>

#define DEFAULTIP "0.0.0.0"
#define DEFAULTPORT "8380"
#define DEFAULTBACK "10"

static void trayExit(GtkMenuItem *item, gpointer user_data);
static void trayIconPopup(GtkStatusIcon *status_icon, guint button, guint32 activate_time, gpointer popUpMenu);
//static gboolean window_state_event (GtkWidget *widget, GdkEventWindowState *event, gpointer user_data);
void updateTrayStatus(GtkWidget *status_icon);
gint sign;
GtkStatusIcon *trayIcon;
static gboolean haveMessage = FALSE;

void prterrmsg(char *msg);
#define prterrmsg(msg)        { perror(msg); abort(); }

void prtinfomsg(char *msg);
#define prtinfomsg(msg)        { fputs(msg, stdout);  }

void startHttp();

#define MAXBUF        1024

char buffer[MAXBUF + 1];
char *host = 0;
char *port = 0;
char *back = 0;
unsigned char daemon_y_n = 0;
#define MAXINPUT        150

int running = 1;

void http_thread(GtkWidget *status_icon) { 
    g_usleep(100000); //一定要加
    // 开始监听http服务
    startHttp(status_icon);
}

int main(int argc, char *argv[])
{
    chdir(dirname(argv[0]));
    
    if (!g_thread_supported()) 
        g_thread_init(NULL); 

    gdk_threads_init();
     
    gtk_init (&argc, &argv);

    //set try icon file 默认图标
    trayIcon  = gtk_status_icon_new_from_file ("./qq.png");
    //set popup menu for tray icon
    GtkWidget *menu, *menuItemExit;
    menu = gtk_menu_new();
    menuItemExit = gtk_menu_item_new_with_label ("Exit");
    g_signal_connect (G_OBJECT (menuItemExit), "activate", G_CALLBACK (trayExit), NULL);
    gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuItemExit);
    gtk_widget_show_all (menu);
    //set tooltip
    gtk_status_icon_set_tooltip (trayIcon, "暂无消息");
    //connect handlers for mouse events
    g_signal_connect(GTK_STATUS_ICON (trayIcon), "popup-menu", GTK_SIGNAL_FUNC (trayIconPopup), menu);
    gtk_status_icon_set_visible(trayIcon, TRUE); //set icon initially invisible

    g_thread_create(http_thread,trayIcon,FALSE,NULL); 
    
    gdk_threads_enter(); 
    gtk_main(); 
    gdk_threads_leave(); 

    return 0;
}

static void trayExit(GtkMenuItem *item, gpointer user_data) 
{
    printf("exit");
    gtk_main_quit();
}

static void trayIconPopup(GtkStatusIcon *status_icon, guint button, guint32 activate_time, gpointer popUpMenu)
{
    gtk_menu_popup(GTK_MENU(popUpMenu), NULL, NULL, gtk_status_icon_position_menu, status_icon, button, activate_time);
}

// 修改托盘图标是否闪烁
void updateTrayStatus(GtkWidget *status_icon){
    // 设置是否闪烁
    gdk_threads_enter();
    gtk_status_icon_set_blinking(GTK_STATUS_ICON (status_icon), haveMessage);
    // 设置托盘tooltip
    gtk_status_icon_set_tooltip (GTK_STATUS_ICON (status_icon), haveMessage?"您有新的消息":"暂无消息");
    gdk_threads_leave();
}

/*------------------------------------------------------
*--- AllocateMemory - 分配空间并把d所指的内容复制
*------------------------------------------------------
*/
void AllocateMemory(char **s, int l, char *d)
{
	*s = malloc(l + 1);
	bzero(*s, l + 1);
	memcpy(*s, d, l);
}

// 开始监听http服务
void startHttp(GtkStatusIcon *status_icon)
{
	struct sockaddr_in addr;
	struct sockaddr_in my_addr;
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	int sock_fd, addrlen;

	if (!host)
	{
		addrlen = strlen(DEFAULTIP);
		AllocateMemory(&host, addrlen, DEFAULTIP);
	}
	if (!port)
	{
		addrlen = strlen(DEFAULTPORT);
		AllocateMemory(&port, addrlen, DEFAULTPORT);
	}
	if (!back)
	{
		addrlen = strlen(DEFAULTBACK);
		AllocateMemory(&back, addrlen, DEFAULTBACK);
	}

	printf("host=%s port=%s back=%s  %s work mode is background(progress ID:%d)\n", host, port, back, daemon_y_n?"":"no", getpid());

	/* fork() 两次处于后台工作模式下 */
	if (daemon_y_n)
	{
		if (fork())
		{
			exit(0);
		}
		if (fork())
		{
			exit(0);
		}
		close(0), close(1), close(2);
	}

	/* 处理子进程退出以免产生僵尸进程 */
	signal(SIGCHLD, SIG_IGN);

	/* 创建 socket */
	if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
	{
		if (!daemon_y_n)
		{
			prterrmsg("socket()");
		}
	}

	/* 设置端口快速重用 */
	addrlen = 1;
	setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,	sizeof(addrlen));

	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(port));
	addr.sin_addr.s_addr = inet_addr(host);//htonl(INADDR_ANY);
	addrlen = sizeof(struct sockaddr_in);
	/* 绑定地址、端口等信息 */
	if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0)
	{
		if (!daemon_y_n)
		{
			prterrmsg("bind()");
		}
	}

	/* 开启临听 */
	if (listen(sock_fd, atoi(back)) < 0)
	{
		if (!daemon_y_n)
		{
			prterrmsg("listen()");
		}
	}
	while (1)
	{
    		g_usleep(10000);
		int len;
		int new_fd;
		addrlen = sizeof(struct sockaddr_in);
		/* 接受新连接请求 */
		new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
		if (new_fd < 0)
		{
			if (!daemon_y_n)
			{
				prterrmsg("accept()");
	        	}
			break;
		}
		bzero(buffer, MAXBUF + 1);
		sprintf(buffer, "connect from: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
		if (!daemon_y_n)
		{
			prtinfomsg(buffer);
		}

		/* 产生一个子进程去处理请求，当前进程继续等待新的连接到来 */
		//if (!fork())			// 改为只有第一次连上能发送数据
		{
			bzero(buffer, MAXBUF + 1);
			if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0)
			{
				FILE *ClientFP = fdopen(new_fd, "w");
				if (ClientFP == NULL)
				{
					if (!daemon_y_n)
					{
						prterrmsg("fdopen()");
					}
					else
					{
						prterrmsg("fdopen()");
					}
				}
				else
				{
					char Req[MAXINPUT + 1] = "";
					sscanf(buffer, "GET /%s HTTP", Req);
					bzero(buffer, MAXBUF + 1);
					sprintf(buffer, "get: \"%s\"\n", Req);
					if (!daemon_y_n)
					{
						prtinfomsg(buffer);
					}
					
					char result[100] = "false";
					if(strcmp(Req,"true")==0) {
						haveMessage = TRUE;
						g_thread_create(updateTrayStatus,status_icon,FALSE,NULL);
						sprintf(result, "ok\r\ny");
					}else if(strcmp(Req,"false")==0){
						haveMessage = FALSE;
						g_thread_create(updateTrayStatus,status_icon,FALSE,NULL); 
						sprintf(result, "ok\r\nn");
					}

					/* 处理用户请求 */
					fprintf(ClientFP, "HTTP/1.1 200 OK\r\n");
					fprintf(ClientFP, "Server:QQMsgTray\r\n");
					fprintf(ClientFP, "Connection: close\r\n");
					fprintf(ClientFP, "Content-Type:text/html; charset=UTF-8\r\n");
					fprintf(ClientFP, "\r\n");
					fprintf(ClientFP, "%s\r\n", result);
					fclose(ClientFP);
				}
			}
			//exit(0);
		}
		close(new_fd);
	}
	close(sock_fd);
}
